package com.woniuxy.user.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.woniuxy.core.annotation.Permission;
import com.woniuxy.core.exception.ParamException;
import com.woniuxy.core.util.Result;
import com.woniuxy.redis.util.RedisUtil;
import com.woniuxy.user.entity.UserLogin;
import com.woniuxy.user.form.*;
import com.woniuxy.user.service.UserLoginService;
import com.woniuxy.user.util.HttpUtils;
import com.woniuxy.user.util.JWTUtil;
import com.woniuxy.user.dto.UserDto;
import com.woniuxy.user.service.UserAccountService;
import com.woniuxy.user.util.TokenUtil;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ...
 * @since 2024年05月22日
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户账号接口")
public class UserAccountController {

    @Resource
    private UserAccountService userAccountService;

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserLoginService userLoginService;
    @Resource
    private  TokenUtil tokenUtil;
    /**
     * 发送用户注册短信
     * @return
     */
    @GetMapping("/sendUserRegist.user")
    @ApiOperation("发送用户注册短信")
    @ApiImplicitParam(name ="userPhone" ,value ="用户手机号" )
    public Result sendUserRegist(String userPhone){
    userAccountService.sendUserRegist(userPhone);
    return Result.success("发送用户注册短信成功",null);
    }


    /**
     * 发送用户修改手机短信
     * @return
     */
    @GetMapping("/sendUserUpdatePhone.user")
    @ApiOperation("发送用户修改手机短信")
    @ApiImplicitParam(name ="userPhone" ,value ="用户手机号" )
    public Result sendUserUpdatePhone(@RequestHeader String token, String userPhone){
        Integer userId = tokenUtil.getUserId(token);
        userAccountService.sendUserUpdatePhone(userId,userPhone);
        return Result.success("发送用户修改手机短信",null);
    }

    /**
     * 发送用户修改新手机短信
     * @return
     */
    @GetMapping("/sendUserUpdateNewPhone.user")
    @ApiOperation("发送用户修改新手机短信")
    @ApiImplicitParam(name ="userPhone" ,value ="用户手机号" )
    public Result sendUserUpdateNewPhone(@RequestHeader String token, String userPhone){
        Integer userId = tokenUtil.getUserId(token);
        userAccountService.sendUserUpdateNewPhone(userId,userPhone);
        return Result.success("发送用户修改新手机短信",null);
    }

    /**
     * 用户修改手机号
     * @param token
     * @param form
     * @return
     */
    @PostMapping("/userUpdatePhone.user")
    @ApiOperation("用户修改手机号")
    public Result userUpdatePhone(@RequestHeader String token,@RequestBody UserUpdatePhoneForm form){
        Integer userId = tokenUtil.getUserId(token);
        userAccountService.userUpdatePhone(userId,form);
        return Result.success("修改手机号成功",null);
    }

    /**
     * 修改密码
     * @param token
     * @param form
     * @return
     */
    @PostMapping("/userUpdatePass.user")
    @ApiOperation("修改密码")
    public Result userUpdatePass(@RequestHeader String token, UserUpdatePassForm form){
        Integer userId = tokenUtil.getUserId(token);
        userAccountService.userUpdatePass(userId,form);
        return Result.success("修改密码成功",null);
    }




    /**
     * 用户注册
     * @param form 注册账号信息参数
     * @return
     */
    @PostMapping("/registUserAccount.user")
    @ApiOperation("用户注册")
    public Result registUserAccount(@Validated @RequestBody RegistUserAccountForm form, BindingResult br){
        if(br.hasErrors()) throw new ParamException(10001,"参数有误");
        userAccountService.registUserAccount(form);
    return Result.success("注册成功",null);
    }

    @GetMapping("/sendLoginCode.user")
    @ApiOperation("发送登录验证码")
    @ApiImplicitParam(name = "userPhone",value = "手机号")
    public Result sendLoginCode(String userPhone){
        userAccountService.sendLoginCode(userPhone);
        return Result.success("发送短信成功",null);
    }

    /**
     *用户验证码登录
     * @param form 用户登录参数
     * @return
     */
    @PostMapping("/userCodeLogin.user")
    @ApiOperation("用户验证码登录")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = UserDto.class)
    })
    public Result userCodeLogin(@RequestBody UserCodeLoginForm form, HttpServletRequest req, HttpServletResponse resp){
        if(ObjectUtil.isEmpty(form.getUserPhone())||ObjectUtil.isEmpty(form.getUserCode())){
            throw new ParamException(10001,"参数有误");
        }
        UserDto dto=  userAccountService.userCodeLogin(form);
        String remoteAddr = req.getRemoteAddr();
        String ipv6="";
        try {
            InetAddress address = InetAddress.getByName("::1"); // 本地IPv6地址，相当于IPv4的127.0.0.1
            ipv6 = address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String url = "http://whois.pconline.com.cn/ipJson.jsp";
        String ip =ipv6;
        String rspStr = HttpUtils.sendGet(url, "ip=" + ip + "&json=true", "GBK");
        JSONObject obj = JSONObject.parseObject(rspStr);
        String region = obj.getString("pro");
        String city = obj.getString("city");
        UserLogin userLogin = new UserLogin();
        userLogin.setUserName(dto.getUserName());
        userLogin.setLoginTime(LocalDateTime.now());
        userLogin.setAddress(city);
        userLogin.setIpAddress(remoteAddr);
        userLoginService.save(userLogin);
        Map<String, Object> map = BeanUtil.beanToMap(dto);
        HashMap<String, Object> accessBody=new HashMap<String, Object>();
        String random=new Snowflake(1,1).nextIdStr();
        accessBody.put("random",random);
        String accessToken= JWTUtil.createUserToken(accessBody,3*24*60);
        String refreshToken=JWTUtil.createUserToken(map,3*24*60);
        redisUtil.set(accessToken,refreshToken);
        resp.setHeader("token",accessToken);
        resp.setHeader("Access-Control-Expose-Headers","token");
        return Result.success("登录成功",dto);
    }

    /**
     *用户账号密码登录
     * @param form 用户登录参数
     * @return
     */
    @PostMapping("/userLogin.user")
    @ApiOperation("用户账号密码登录")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = UserDto.class)
    })
    public Result userLogin(@RequestBody UserLoginForm form,HttpServletRequest req, HttpServletResponse resp){
        if(ObjectUtil.isEmpty(form.getUserName())||ObjectUtil.isEmpty(form.getUserPass())){
            throw new ParamException(10001,"参数有误");
        }
        UserDto dto=  userAccountService.userLogin(form);
        String remoteAddr = req.getRemoteAddr();
        String ipv6="";
        try {
            InetAddress address = InetAddress.getByName("::1"); // 本地IPv6地址，相当于IPv4的127.0.0.1
            ipv6 = address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String url = "http://whois.pconline.com.cn/ipJson.jsp";
        String ip =ipv6;
        String rspStr = HttpUtils.sendGet(url, "ip=" + ip + "&json=true", "GBK");
        JSONObject obj = JSONObject.parseObject(rspStr);
        String region = obj.getString("pro");
        String city = obj.getString("city");
        UserLogin userLogin = new UserLogin();
        userLogin.setUserName(dto.getUserName());
        userLogin.setLoginTime(LocalDateTime.now());
        userLogin.setAddress(city);
        userLogin.setIpAddress(remoteAddr);
        userLoginService.save(userLogin);
        Map<String, Object> map = BeanUtil.beanToMap(dto);
        HashMap<String, Object> accessBody=new HashMap<String, Object>();
        String random=new Snowflake(1,1).nextIdStr();
        accessBody.put("random",random);
        String accessToken= JWTUtil.createUserToken(accessBody,15);
        String refreshToken=JWTUtil.createUserToken(map,3*24*60);
        redisUtil.set(accessToken,refreshToken);
        resp.setHeader("token",accessToken);
        resp.setHeader("Access-Control-Expose-Headers","token");
        return Result.success("登录成功",dto);
    }

    /**
     * 修改用户状态
     * @param userId 用户Id
     * @param state 用户状态
     * @return
     */
    @GetMapping("/updateUserState")
    @ApiOperation("修改用户状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户ID"),
            @ApiImplicitParam(name = "state",value = "状态")
    })
    @Permission(roles = {"超级管理员","管理员"})
    public Result updateUserState(Integer userId,Integer state){
     userAccountService.updateUserState(userId,state);
    return Result.success("修改用户状态成功",null);
    }








}

